package com.polidea.rxohosble2.internal.operations;

import com.polidea.rxohosble2.internal.SingleResponseOperation;
import com.polidea.rxohosble2.internal.connection.ConnectionModule;
import com.polidea.rxohosble2.internal.connection.RxBleGattCallback;
import com.polidea.rxohosble2.internal.logger.LoggerUtil;
import com.polidea.rxohosble2.internal.util.ByteAssociation;
import com.polidea.rxohosble2.internal.util.ByteAssociationUtil;
import com.polidea.rxohosble2.exceptions.BleGattOperationType;

import bleshadow.javax.inject.Inject;
import bleshadow.javax.inject.Named;

import io.reactivex.Single;
import ohos.bluetooth.ble.BlePeripheralDevice;
import ohos.bluetooth.ble.GattDescriptor;

public class DescriptorReadOperation extends SingleResponseOperation<ByteAssociation<GattDescriptor>> {

    private final GattDescriptor bluetoothGattDescriptor;

    @Inject
    DescriptorReadOperation(RxBleGattCallback rxBleGattCallback, BlePeripheralDevice bluetoothGatt,
                            @Named(ConnectionModule.OPERATION_TIMEOUT) TimeoutConfiguration timeoutConfiguration,
                            GattDescriptor descriptor) {
        super(bluetoothGatt, rxBleGattCallback, BleGattOperationType.DESCRIPTOR_READ, timeoutConfiguration);
        bluetoothGattDescriptor = descriptor;
    }

    @Override
    protected Single<ByteAssociation<GattDescriptor>> getCallback(RxBleGattCallback rxBleGattCallback) {
        return rxBleGattCallback
                .getOnDescriptorRead()
                .filter(ByteAssociationUtil.descriptorPredicate(bluetoothGattDescriptor))
                .firstOrError();
    }

    @Override
    protected boolean startOperation(BlePeripheralDevice bluetoothGatt) {
        return bluetoothGatt.readDescriptor(bluetoothGattDescriptor);
    }

    @Override
    public String toString() {
        return "DescriptorReadOperation{"
                + super.toString()
                + ", descriptor=" + LoggerUtil.wrap(bluetoothGattDescriptor, false)
                + '}';
    }
}
